package com.lxf.project;

import com.lxf.project.inteface.IHelloWorld;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.utils.ReferenceConfigCache;
import org.apache.dubbo.rpc.RpcContext;
import sun.applet.Main;

public class DubboDemoApiConsumer {
    public static void main(String[] args) throws InterruptedException {
//        runWithBootstrap();
          contextTest();
    }


    /**
     * 上下文測試
     */
    private static void contextTest() {
        ReferenceConfig<IHelloWorld> reference = new ReferenceConfig<>();
        reference.setInterface(IHelloWorld.class);
        reference.setGeneric("true");
        DubboBootstrap bootstrap = DubboBootstrap.getInstance();
        ApplicationConfig applicationConfig = new ApplicationConfig("dubbo-demo-api-consumer");
        applicationConfig.setQosPort(33331);
        bootstrap.application(applicationConfig)
                .registry(new RegistryConfig("zookeeper://127.0.0.1:2181"))
                .reference(reference)
                .start();

        IHelloWorld demoService = ReferenceConfigCache.getCache().get(reference);
        String message = demoService.sayHello("dubbo:dubbo-demo-api-consumer");
        System.out.println(message);
        RpcContext rpcContext =  RpcContext.getContext();
//        boolean boo =  rpcContext.isConsumerSide();
//        System.out.println("本端是否为消费方：" + boo);
        String serverIP =rpcContext.getRemoteHost();
        System.out.println("获取最后一次调用的api地址："+serverIP);

        String application = rpcContext.getUrl().getParameter("application");
        System.out.println("获取当前服务配置信息，所有配置信息都将转换为URL的参数："+application);
        // 注意：每发起RPC调用，上下文状态会变化
        String message1 = demoService.sayHello("dubbo:dubbo-demo-api-consumer1");
        System.out.println("获取当前服务配置信息，所有配置信息都将转换为URL的参数："+application);



    }
    /**
     * demo测试
     */

    private static void runWithBootstrap() throws InterruptedException {
        ReferenceConfig<IHelloWorld> reference = new ReferenceConfig<>();
        reference.setInterface(IHelloWorld.class);
        reference.setGeneric("true");
        DubboBootstrap bootstrap = DubboBootstrap.getInstance();
        ApplicationConfig applicationConfig = new ApplicationConfig("dubbo-demo-api-consumer");
        applicationConfig.setQosPort(33331);
        bootstrap.application(applicationConfig)
                .registry(new RegistryConfig("zookeeper://127.0.0.1:2181"))
                .reference(reference)
                .start();

        IHelloWorld demoService = ReferenceConfigCache.getCache().get(reference);
        int count =0;
        for (;;){
            count ++;
            String message = demoService.sayHello("dubbo:"+ count);
            System.out.println(message);
            Thread.sleep(100);
        }


    }

}
